package org.jzyan.framework.registry.endpoint;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.registry.NacosRegistration;
import com.alibaba.cloud.nacos.registry.NacosServiceRegistry;
import lombok.extern.log4j.Log4j2;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;

/**
 * <p>
 * 从nacos中下线副本的API
 * </p>
 *
 * @author jzyan
 * @since 2023-02-17
 */
@Log4j2
@Endpoint(id = "nacosderegister")
public class NacosServiceDeregisterEndpoint {
    private NacosDiscoveryProperties nacosDiscoveryProperties;
    private NacosRegistration nacosRegistration;
    private NacosServiceRegistry nacosServiceRegistry;

    public NacosServiceDeregisterEndpoint(NacosDiscoveryProperties nacosDiscoveryProperties, NacosRegistration nacosRegistration, NacosServiceRegistry nacosServiceRegistry) {
        this.nacosDiscoveryProperties = nacosDiscoveryProperties;
        this.nacosRegistration = nacosRegistration;
        this.nacosServiceRegistry = nacosServiceRegistry;
    }

    /**
     * 从 nacos 中主动下线应用
     *
     * @return
     */
    @ReadOperation
    public String deregister() {
        String serviceName = nacosDiscoveryProperties.getService();
        String groupName = nacosDiscoveryProperties.getGroup();
        String clusterName = nacosDiscoveryProperties.getClusterName();
        String ip = nacosDiscoveryProperties.getIp();
        int port = nacosDiscoveryProperties.getPort();
        log.info("从Nacos注册中心下线服务, 服务名:{}, 分组名:{}, 集群名:{}, IP:{}, PORT:{}", serviceName, groupName,
                clusterName, ip, port);
        // 设置服务下线
        nacosServiceRegistry.setStatus(nacosRegistration, "DOWN");
        return "success";
    }

}
